package com.util;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * ͼƬ�ϴ�������
 * 
 * @author Pudding
 * 
 */
@Component
public class FileUtils {

	/**
	 * 图片文件类型
	 * 
	 * @author Administrator
	 * 
	 */
	public enum ImageType {
		bmp, jpeg, gif, tiff
	}

	/**
	 * 通用文件上传
	 * 
	 * @param item
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> commonFileUpload(FileItem item,
			String path) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		if (path.isEmpty()) {
			throw new IllegalArgumentException("保存目录不能为空[" + path + "]!");
		}
		System.out.println("============" + path);
		String newFilePath = null;
		String origiFileName = null;
		String prefix = null;

		// 保存文件
		try {
			buildFileDirectory(path);
			origiFileName = item.getName();
			prefix = origiFileName.substring(origiFileName.lastIndexOf("."));// 截取文件类型
			String randomNumber = UUID.randomUUID().toString()
					.replaceAll("-", "");
			// 新保存文件绝对路�?
			// newFilePath = path + SEPARATOR + randomNumber + prefix;
			newFilePath = randomNumber + prefix;
			System.out.println("newFilePath" + newFilePath);
			map.put("file", randomNumber + prefix);
			map.put("path", newFilePath);

			File finalUploadFile = new File(path, newFilePath);
			finalUploadFile.setWritable(true, false);
			System.out.println("gggg" + finalUploadFile);
			item.write(finalUploadFile);
			System.out.println("dddd" + path);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	/**
	 * 文件目录创建方法
	 * 
	 * @param path
	 */
	public static void buildFileDirectory(String path) {
		File uploadFilePath = new File(path);
		// 如果该目录不存在,则创建之
		if (uploadFilePath.exists() == false) {
			uploadFilePath.mkdirs();
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param response
	 * @param filePath
	 * @param fileName
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void getFile(HttpServletResponse response, String filePath,
                               String fileName) throws FileNotFoundException, IOException {
		// 获取当前操作系统的字符集
		String encoding = System.getProperty("sun.jnu.encoding");
		// 根据当前系统的字符集设置响应�?
		response.setContentType("text/html;charset=" + encoding);
		InputStream in = null;
		byte[] tmp = null;
		// 相应头文件长�?
		long fileLength = new File(filePath).length();
		// 设置为下�?
		response.setContentType("application/x-msdownload;");
		// 设置下载时输出的文件�?
		String[] type = fileName.split("\\.");
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String outPutFileName = format.format(new Date()) + "." + type[1];
		// 设置响应�?
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(outPutFileName.getBytes(encoding), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));
		try {
			in = new FileInputStream(filePath);
			tmp = new byte[in.available()];
			in.read(tmp);
			ServletOutputStream out = response.getOutputStream();
			out.write(tmp);
			out.flush();
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}

	/**
	 * 获取图片预览地址
	 * 
	 * @param response
	 * @param filePath
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public static void getPicPreview(HttpServletResponse response,
			String filePath, ImageType imageType) throws FileNotFoundException,
			IOException {
		InputStream in = null;
		byte[] tmp = null;
		// 设置响应数据类型
		response.setContentType("image/" + imageType.name());
		try {
			// 获取图片
			in = new FileInputStream(filePath);
			// in.available返回实际可读的字节数 保证tmp与实际的图片文件大小�?�?
			tmp = new byte[in.available()];
			in.read(tmp);
			ServletOutputStream out = response.getOutputStream();
			// 写入文件到输出流
			out.write(tmp);
			// 清空输出流将未写入的字节全部写入输出�?
			out.flush();
		} finally {
			if (in != null) {
				in.close();
			}
		}
	}

	public static String deleteFile(String path, String fileUuidName) {
		String newPath = path + fileUuidName;
		File file = new File(newPath);
		if (file.isFile() && file.exists()) {
			file.delete();
			return "文件删除成功";
		} else {
			return "文件删除失败";
		}
	}
}